<?php

	$GLOBALS['sortByValues'] = array('ticket', 'received', 'senderName', 'senderEmail', 'subject', 'tech', 'status');

	/* The admin page that displays all of the submitted tickets */
	require_once('/admin_header.php');
	require_once('ticket_functions.php');
	if($_SERVER['REQUEST_METHOD'] == 'POST'):
		handlePost();		
	elseif ($_SERVER['REQUEST_METHOD'] == 'GET'):
		renderTicketTable(false);
	endif;
	
	function handlePost()
	{
		if(isset($_POST['logoutSubmit'])):
			destroySession();
			forgetRememberMeCookie();
			header("Location: /proj2/admin_login.php");
		elseif(isset($_POST['sortBySubmit'])):
			renderTicketTable(true);
		elseif(isset($_POST['viewSelectedTicketSubmit'])):
			handleViewSelectedTicketSubmit();
		elseif(isset($_POST['viewAllTicketsSubmit'])):
			renderTicketTable(true);
		elseif(isset($_POST['viewMyTicketsSubmit'])):
			renderTicketTable(true);
		elseif(isset($_POST['viewUnassignedTicketsSubmit'])):
			renderTicketTable(true);
		elseif(isset($_POST['viewOpenTicketsSubmit'])):
			renderTicketTable(true);
		else:
			echo "Receieved unhandled POST request<br/>";
		endif;	
	}
	
	function handleViewSelectedTicketSubmit()
	{
		$ticketNumberToDisplay = $_POST['selectedTicket'];
		displayTicketToUser($ticketNumberToDisplay);
	}
	
	function displayTicketToUser($ticketNumberToDisplay)
	{
		header("Location: /proj2/display_ticket.php?ticketID=" . $ticketNumberToDisplay);
	}
	
	function renderTicketTable($isPost)
	{
		renderTicketTableHeader($isPost);
		recordLastTypeOfTicketButtonSubmission($isPost);
		recordFilterFromDisplayTicketsPage($isPost);
		renderTicketsInTable($isPost);
		renderTicketTableFooterAndButtons($isPost);
	}
	
	function recordLastTypeOfTicketButtonSubmission($isPost)
	{
		/* We use a hidden field in the submitted form to keep track of what query to use
			when the sort button is pressed. We need this hidden variable to differentiate between
			assigned- / unassigned- / my-tickets-button presses.
			*/
		$default = 'viewAllTicketsSubmit';
		if($isPost):
			if(isset($_POST['viewAllTicketsSubmit'])):
				$GLOBALS['LastTypeOfTicketButtonSubmission'] = $default;
			elseif(isset($_POST['viewMyTicketsSubmit'])):
				$GLOBALS['LastTypeOfTicketButtonSubmission'] = 'viewMyTicketsSubmit';
			elseif(isset($_POST['viewUnassignedTicketsSubmit'])):
				$GLOBALS['LastTypeOfTicketButtonSubmission'] = 'viewUnassignedTicketsSubmit';
			elseif(isset($_POST['viewOpenTicketsSubmit'])):
				$GLOBALS['LastTypeOfTicketButtonSubmission'] = 'viewOpenTicketsSubmit';
			else:
				/* Sort was pressed (logout and view selected tickets button presses
					will navigate away from the
					admin page, so we can forget about queries for this page). */
				$GLOBALS['LastTypeOfTicketButtonSubmission'] = $_POST['LastTypeOfTicketButtonSubmission'];
			endif;
		else:
			$GLOBALS['LastTypeOfTicketButtonSubmission'] = $default;
		endif;
		$lastTypeOfTicketButtonSubmission = $GLOBALS['LastTypeOfTicketButtonSubmission'];
		echo "<input type='hidden' name='LastTypeOfTicketButtonSubmission' value='$lastTypeOfTicketButtonSubmission' >\n";
	}
	
	function recordFilterFromDisplayTicketsPage($isPost)
	{	
		// echo "<br/>recordFilterFromDisplayTicketsPage \$isPost: $isPost get:<br/>";
		// var_dump($_GET);
		// echo "<br/>recordFilterFromDisplayTicketsPage post:<br/>";
		// var_dump($_POST);
		
		if($isPost):
			if(isset($_POST['senderEmail'])):	
				$senderEmail = $_POST['senderEmail'];
				if(!isset($_POST['sortBySubmit'])):
					unset($_POST['senderEmail']);
				else:
					echo "<input type='hidden' name='senderEmail' value='$senderEmail' >\n";
				endif;
				// TODO:
				// check the createQuery function for sort
			elseif(isset($_POST['similarSubject'])):
				$similarSubject = $_POST['similarSubject'];
				if(!isset($_POST['sortBySubmit'])):
					unset($_POST['similarSubject']);
				else:
					echo "<input type='hidden' name='similarSubject' value='$similarSubject' >\n";
				endif;
				// TODO:
				// check the createQuery function for sort			
			else:
				return;
			endif;
		else:
			if(isset($_GET['senderEmail'])):	
				$senderEmail = $_GET['senderEmail'];
				echo "<input type='hidden' name='senderEmail' value='$senderEmail' >\n";
			elseif(isset($_GET['similarSubject'])):
				$similarSubject = $_GET['similarSubject'];
				echo "<input type='hidden' name='similarSubject' value='$similarSubject' >\n";			
			else:
				return;
			endif;
		endif;
	}
	
	function renderTicketTableHeader($isPost)
	{
		if($isPost):
			$file = file('ticket_table\table_header_without_sort.html');
			foreach($file as $line):
				echo $line;
			endforeach;
			// print_r($_POST);
			$currentSortByValue = $_POST['selectedSort'];
			renderSortRow($currentSortByValue);
		else:
			$file = file('ticket_table\table_header.html');
			foreach($file as $line):
				echo $line;
			endforeach;
		endif;
	}
	
	function renderSortRow($currentSortByValue)
	{
		$sortByValues = $GLOBALS['sortByValues'];
		for($i = 0; $i < count($sortByValues); $i++):
			if(strcmp($sortByValues[$i], $currentSortByValue) == 0):
				echo '<td>Sort by ' . "<input checked type='radio' name='selectedSort' value='" . 
						$sortByValues[$i] . "'>" . '</td>';
			else:
				echo '<td>Sort by ' . "<input type='radio' name='selectedSort' value='" . 
						$sortByValues[$i] . "'>" . '</td>';
			endif;
		endfor;
	}
	
	function renderTicketTableFooterAndButtons($isPost)
	{
		/* $file = file('ticket_table\table_footer_and_buttons.html');
		foreach($file as $line):
			echo $line;
		endforeach;
		 */
		echo '</table>';
		echo '<div style="width:680px; min-height: 50px; background-color:#EEE; margin: 5px auto; padding:10px;
			border-radius:5px;">';
		displayStaticButtons();
		displayDynamicButtons($isPost);
		echo '</div>';
	}
	
	function displayDynamicButtons($isPost)
	{
		echo '<div style="margin:10px; text-align:center;">';
		$default = 	'<input style="margin-right:50px; width: 170px;" type="submit" name="viewMyTicketsSubmit" value="View My Tickets">				
					<input style="margin-right:50px; width: 170px;" type="submit" name="viewUnassignedTicketsSubmit" value="View Unassigned Tickets">
					<input style="width: 170px;" type="submit" name="viewOpenTicketsSubmit" value="View Open Tickets">
					';
		if($isPost):
			if(isset($_POST['viewAllTicketsSubmit'])):
				echo	'<input style="margin-right:50px; width: 170px;" type="submit" name="viewMyTicketsSubmit" value="View My Tickets">				
						<input style="margin-right:50px; width: 170px;" type="submit" name="viewUnassignedTicketsSubmit" value="View Unassigned Tickets">
						<input style="width: 170px;" type="submit" name="viewOpenTicketsSubmit" value="View Open Tickets">
						';
			elseif(isset($_POST['viewMyTicketsSubmit'])):
				echo	'<input style="margin-right:50px; width: 170px;" type="submit" name="viewAllTicketsSubmit" value="View All Tickets">
						<input style="margin-right:50px; width: 170px;" type="submit" name="viewUnassignedTicketsSubmit" value="View Unassigned Tickets">
						<input style="width: 170px;" type="submit" name="viewOpenTicketsSubmit" value="View Open Tickets">
						';
			elseif(isset($_POST['viewUnassignedTicketsSubmit'])):
				echo	'<input style="margin-right:50px; width: 170px;" type="submit" name="viewAllTicketsSubmit" value="View All Tickets">
						<input style="margin-right:50px; width: 170px;" type="submit" name="viewMyTicketsSubmit" value="View My Tickets">
						<input style="width: 170px;" type="submit" name="viewOpenTicketsSubmit" value="View Open Tickets">
						';
			elseif(isset($_POST['viewOpenTicketsSubmit'])):
				echo	'<input style="margin-right:50px; width: 170px;" type="submit" name="viewAllTicketsSubmit" value="View All Tickets">
						<input style="margin-right:50px; width: 170px;" type="submit" name="viewMyTicketsSubmit" value="View My Tickets">
						<input style="width: 170px;" type="submit" name="viewUnassignedTicketsSubmit" value="View Unassigned Tickets">
						';
			else:
				echo $default;
			endif;
		else:
			/* default for get */
			echo $default;				
		endif;
		
		echo '</div>';
	}
	
	function displayStaticButtons()
	{
		echo staticButtons();
	}
	
	function staticButtons()
	{
		?>
		<div style="margin:10px; text-align:center;">				
			<input style="margin-right:50px; width: 170px;" type='submit' name='logoutSubmit' value='Logout'>
			<input style="margin-right:50px; width: 170px;" type='submit' name='sortBySubmit' value='Sort'>
			<input style="width: 170px;" type='submit' name='viewSelectedTicketSubmit' value='View Selected Ticket'>
		</div>
		<?php
	}
	
	function renderTicketsInTable($isPost)
	{
		require("private\mysqli_connect.php");
		$errorMessage = "<div style='text-align:center;'>There are no tickets to display.</div>";
		
		if(getNumberOfTickets() > 0):
			$query = createTicketsQuery($isPost);
			// echo "<br/><br/> $query<br/><br/>";
			$result = $db->query($query);
			if(!$result):
				echo $errorMessage;
				return false;
			endif;
			$rows = $result->num_rows;
			// echo "<br/>" . var_dump($db->error) . "<br/>";
			for($i = 0; $i < $rows; $i++):
				$row = $result->fetch_array();
				echo "<tr>";	
				renderRowInTable($row,$i);
				echo "</tr>";
			endfor;
			return true;
		else:
			echo $errorMessage;
			return false;
		endif;		
	}
	
	function queryWasSuccessful($db)
	{
		if(strcmp($db->error, "") == 0):
			return true;
		else:
			return false;
		endif;
	}
	
	function createTicketsQuery($isPost)
	{
		static $calls = 0;	
		$calls++;
		// echo "<br/>createTicketsQuery is being called for time $calls.</br>";
		// if(isset($_POST['viewUnassignedTicketsSubmit'])):
			// echo "<br/>we are viewing unassigned tickets";
		// endif;
		$sortBy = ' order by ' . getTicketSortByValueForDatabase("asc", $isPost);
		$defaultQuery = "select * from tickets left join administrators on tickets.administrator_id = administrators.admin_id"
				. $sortBy;
		// echo "<br/>\$_POST: ";
		// var_dump($_POST);
		// echo "<br/>";
		
		if(!isset($_POST['senderEmail']) && !isset($_GET['senderEmail']) && !isset($_POST['similarSubject']) && !isset($_GET['similarSubject'])):
			if($isPost):
				if(isset($_POST['viewAllTicketsSubmit'])):
					return $defaultQuery;
				/* elseif(isset($_POST['sortBySubmit'])):
					unset($_POST['sortBySubmit']);
					$LastTypeOfTicketButtonSubmission = $_POST['LastTypeOfTicketButtonSubmission'];
					// echo "<br/>\$LastTypeOfTicketButtonSubmission: ";
					// echo var_dump($LastTypeOfTicketButtonSubmission) . "<br/>";
					
					$_POST[$LastTypeOfTicketButtonSubmission] = 1;
					//$_POST['viewUnassignedTicketsSubmit'] = 1;
					// Call this function again except we know what what query we need 
						// the next call because we recorded the ticket type (all / my / unassigned)
						// in the hidden field. 
					return createTicketsQuery($isPost); */
				elseif(isset($_POST['sortBySubmit'])):					
					unset($_POST['sortBySubmit']);
					$LastTypeOfTicketButtonSubmission = $_POST['LastTypeOfTicketButtonSubmission'];
					// echo "<br/>\$LastTypeOfTicketButtonSubmission: ";
					// echo var_dump($LastTypeOfTicketButtonSubmission) . "<br/>";
					
					$_POST[$LastTypeOfTicketButtonSubmission] = 1;
					//$_POST['viewUnassignedTicketsSubmit'] = 1;
					// Call this function again except we know what what query we need 
						// the next call because we recorded the ticket type (all / my / unassigned)
						// in the hidden field. 
					return createTicketsQuery($isPost);
				elseif(isset($_POST['viewSelectedTicketSubmit'])):
					// handled by other code
				elseif(isset($_POST['viewMyTicketsSubmit'])):
					$adminUsername = $_SESSION['admin_username'];
					$query = "select * from tickets join administrators on tickets.administrator_id = administrators.admin_id
							where administrators.username = '" . $adminUsername . "'" .$sortBy;
					return $query;
				elseif(isset($_POST['viewOpenTicketsSubmit'])):
					$query = "select * from tickets left join administrators on tickets.administrator_id = administrators.admin_id 
							where tickets.ticket_is_open = true" . $sortBy;
					return $query;
				elseif(isset($_POST['logoutSubmit'])):
					destroySession();
					forgetRememberMeCookie();
					header("Location: /proj2/admin_login.php");
				elseif(isset($_POST['viewUnassignedTicketsSubmit'])):
					$query = "select * from tickets left join administrators on tickets.administrator_id = administrators.admin_id" .
							" where tickets.administrator_id < 1 or tickets.administrator_id is null"
									. $sortBy;
					return $query;
				else:
					echo "<br/><br/>There was an error creating the query in createTicketsQuery()</br></br>";
					return $defaultQuery;
				endif;			
			else:
				return $defaultQuery;
			endif;
		else:
			// TODO:
			// Display_tickets wants us to filter by sender email or ticket subject
			return createFilterQueryForSortBySubmit($sortBy, $isPost);
		endif;
	}
	
	function createFilterQueryForSortBySubmit($sortBy, $isPost)
	{
		if(isset($_POST['senderEmail'])):
			$query = 	"select * from tickets left join administrators on tickets.administrator_id = administrators.admin_id
						where sender_email = '" . str_replace(" " , '+', $_POST['senderEmail']) . "' $sortBy";
			return $query;
		elseif(isset($_GET['senderEmail'])):
			$query = 	"select * from tickets left join administrators on tickets.administrator_id = administrators.admin_id
						where sender_email = '" . str_replace(" " , '+', $_GET['senderEmail']) . "' $sortBy";
			return $query;
		elseif(isset($_POST['similarSubject'])):
			$similarSubject = $_POST['similarSubject'];
			$words = explode(' ', $similarSubject);
			
			$query = 	"select * from tickets left join administrators on tickets.administrator_id = administrators.admin_id";
			foreach($words as $key => $word):
				if($key == 0):
					$query .= " where subject like '%" . $word . "%'";
				elseif($key > 0):
					$query .= " or subject like '%" . $word . "%'";
				endif;
			endforeach;
			return $query . $sortBy;
		elseif(isset($_GET['similarSubject'])):
			$similarSubject = $_GET['similarSubject'];
			$words = explode(' ', $similarSubject);
			
			$query = 	"select * from tickets left join administrators on tickets.administrator_id = administrators.admin_id";
			foreach($words as $key => $word):
				if($key == 0):
					$query .= " where subject like '%" . $word . "%'";
				elseif($key > 0):
					$query .= " or subject like '%" . $word . "%'";
				endif;
			endforeach;
			return $query . $sortBy;
		else:
			return "adjsemhvtseruvnhs";
		endif;
	}
	
	function getTicketSortByValueForDatabase($direction, $isPost)
	{
		if(!$isPost):
			return "tickets.ticket_id $direction";
		endif;
		switch($_POST['selectedSort'])
		{
			case 'ticket':
				return "tickets.ticket_id $direction";				
			case 'received':
				return "received $direction";				
			case 'senderName':
				return "sender_lastname $direction, sender_firstname $direction";				
			case 'senderEmail':
				return "sender_email $direction";				
			case 'subject':
				return "subject $direction";
			case 'tech':
				return "username $direction";
			case 'status':
				return "ticket_is_open $direction";		
			default:
				return "tickets.ticket_id $direction";
		}
		
	}
	
	function renderRowInTable($row, $rowNumber)
	{	
		$ticketID = $row['ticket_id'];
		//echo "<br/><br/>row dump: " . var_dump($row);
		echo "<td>" . $ticketID . "</td>";
		echo "<td>" . $row['received'] . "</td>";
		echo "<td>" . $row['sender_firstname'] . ' ' . $row['sender_lastname']. "</td>";
		echo "<td>" . $row['sender_email'] . "</td>";
		echo "<td>" . $row['subject'] . "</td>";
		
		$adminUsername = getAdminNameByID($row['administrator_id']);
		echo "<td>" . $adminUsername . "</td>";
		if($row['ticket_is_open']):
			echo '<td>open</td>';	
		else:
			echo '<td>closed</td>';	
		endif;
		/* check the first row */
		if($rowNumber == 0): 
			echo "<td><input checked type='radio' name='selectedTicket' value='$ticketID'></td>";
		else:
			echo "<td><input type='radio' name='selectedTicket' value='$ticketID'></td>";
		endif;
		
	}
	
	function getNumberOfTickets()
	{
		require("private\mysqli_connect.php");
		$result = $db->query("select tickets.ticket_id from tickets");
		return $result->num_rows;
	}
?>